const fs = require('fs-extra');
const path = require('path');
const { getFileHash } = require('./handy');

exports.convertImageToPdf = async function (imageFilePath, pdfFilePath) {
    const { PDFDocument } = (await import('pdf-lib')).default;
    console.log('把图片转换为pdf');
    console.log('原始图片地址: ' + imageFilePath);
    const imageExt = path.extname(imageFilePath);
    if (!pdfFilePath) {
        console.log('保存PDF到图片目录');
        const dirName = path.dirname(imageFilePath);
        const baseName = path.basename(imageFilePath, imageExt);
        pdfFilePath = path.join(dirName, baseName + '.pdf');
    }
    console.log('转换后的pdf地址：' + pdfFilePath);
    /** @type {PDFDocument} */
    const pdfDoc = await PDFDocument.create();
    const imageBuffer = await fs.readFile(imageFilePath);
    let pdfImage;
    if (imageExt === '.png') {
        pdfImage = await pdfDoc.embedPng(imageBuffer);
    } else if (['.jpg', '.jpeg'].includes(imageExt)) {
        pdfImage = await pdfDoc.embedJpg(imageBuffer);
    } else {
        console.log('无法转换PDF的图片格式：' + imageExt);
        throw new Error('暂不支持的图片格式');
    }
    const page = pdfDoc.addPage();
    const pageWidth = page.getWidth();
    const pageHeight = page.getHeight();
    page.drawImage(pdfImage, {
        x: 0,
        y: 0,
        // 完全填满整个PDF页面
        width: pageWidth,
        height: pageHeight,
    });
    const pdfBytes = await pdfDoc.save(pdfFilePath);
    console.log('图片->pdf 转换结束');
    fs.writeFileSync(pdfFilePath, pdfBytes);
    return pdfFilePath;
};

exports.pdfToImg = async function (pdfFilePath) {
    console.log('转换pdf->图片');
    console.log('pdf: ' + pdfFilePath);
    const { pdf } = await import('pdf-to-img');
    const pdfHash = await getFileHash(pdfFilePath);
    const pdfDir = path.dirname(pdfFilePath);
    const pdfBaseName = path.basename(pdfFilePath, '.pdf');
    const imageDir = path.join(pdfDir, pdfHash);
    fs.mkdirp(imageDir);
    const document = await pdf(pdfFilePath, { scale: 1 });
    const imageList = [];
    let index = 1;
    for await (const image of document) {
        const imageFileName = `${pdfBaseName}_${index}.png`;
        const imageFilePath = path.join(imageDir, imageFileName);
        console.log(`生成图片：${imageFilePath}`);
        // 不需要等待文件写完
        fs.writeFile(imageFilePath, image);
        imageList.push({
            imageFileName,
        });
        index++;
    }
    return imageList;
};
